﻿using System;

using System.IO;

namespace sublight_sv
{
    internal class AvsLauncherException : Exception
    {
        internal AvsLauncherException(string message) : base(message)
        {
            
        }
    }

    internal static class AvsLauncher
    {
        public static void Launch(string dirName, string player, string video, string port)
        {
            var scriptPath = dirName + @"\script.avs";

            var arguments = player.Replace("\"", "").
                Split(new[] {@".exe"}, StringSplitOptions.None);

            var file = new StreamWriter(scriptPath);

            file.WriteLine(@"# This script was automatically generated by Sublight Server");
            file.WriteLine(String.Format(@"LoadPlugin(""{0}\as_sublight.dll"")",
                                         dirName));
            file.WriteLine(String.Format(@"return Sublight(DirectShowSource(""{0}""), PORT={1}, IP=""{2}"")",
                                         video,
                                         port,
                                         @"255.255.255.255"));
            file.Close();

            var prc = new System.Diagnostics.Process
                          {
                              StartInfo =
                                  {
                                      FileName = arguments[0] + @".exe",
                                      Arguments =
                                          ((arguments.Length > 1) ? arguments[1] : "") + " \"" + scriptPath + "\""
                                  }
                          };

            if (prc.StartInfo.FileName.Length == 0)
            {
                throw new AvsLauncherException(@"Player was not selected");
            }

            try
            {
                prc.Start();
            }
            catch (System.ComponentModel.Win32Exception)
            {
                prc.WaitForExit();
                prc.Close();
                throw new AvsLauncherException(@"Invalid player filename");
            }
            prc.WaitForExit();
            prc.Close();

            File.Delete(scriptPath);
        }
    }
}
